iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 27
0
Modern Web

30天React從入門到入坑系列 第 27

DAY27:react-redux simple counter

  • 分享至 

  • xImage
  •  

react redux diagram
https://ithelp.ithome.com.tw/upload/images/20180115/201073171t0nKvh5Bz.png

view觸發事件->dispatch發送action->reducer根據action返回新的state->store接受state更新->更新view


actions純js物件,包含type讓reducer判斷處理其於由使用者自訂。

src/action.js

export const INCREMENT = () => {
  return {
    type: 'INCREMENT',
    count: 1
  }
};

export const DECREMENT = () => {
  return {
    type: 'DECREMENT',
    count: -1
  }  
};

Counter Component
mapStateToProps:接受由reducer傳來的state
mapDispatchToProps:接收dispatch參數(dispatch為Store的方法),定義發送事件的方法
connect:把component與store串在一起,所以state可以轉成props傳遞下去

src/Counter.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as actions from './actions';
import { connect } from 'react-redux';

class Counter extends React.Component {
  render () {
    const { count, onClickPlus, onClickMinus } = this.props;
    return (
      <div>
        <p><span>Count: {count}</span></p>
        <div>
          <button onClick={onClickPlus}>+1</button>
          <button onClick={onClickMinus}>-1</button>
        </div>
      </div>
    );
  }
}

Counter.propTypes = {
  count: PropTypes.number.isRequired,
  onClickPlus: PropTypes.func.isRequired,
  onClickMinus: PropTypes.func.isRequired
};

function mapStateToProps (state) {
  return {
    count: state.count
  };
}

function mapDispatchToProps (dispatch) {
  return {
    onClickPlus: () => dispatch(actions.INCREMENT()),
    onClickMinus: () => dispatch(actions.DECREMENT())
  };
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter);

reducer產生新的state回傳

src/reducer.js

export default (state = {count: 0}, action) => {
  let count = state.count;
  switch (action.type) {
    case 'INCREMENT':
      return {count: count + action.count};
    case 'DECREMENT':
      return {count: count + action.count};
    default:
      return state;
  }
}

Provider提供store給所有的component

src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import reducer from './reducer';
import Counter from './Counter';

let store = createStore(reducer);

ReactDOM.render(
  <Provider store={store}>
    <Counter />
  </Provider>,
  document.getElementById('app')
);

github repositories react-redux-counter
https://github.com/kwon44/react-redux-counter

參考資料
Redux
https://redux.js.org/


上一篇
DAY26:用counter來了解redux
下一篇
DAY28:react-redux middleware做什麼?
系列文
30天React從入門到入坑30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言